#蓝图
from flask import Blueprint, views, render_template, request, session, redirect, url_for, g
from .forms import LoginForm, RestpwdForm, ResetEmailForm
from .models import CMSUser
from .decorators import login_required
import config
from exts import db, mail
from flask_mail import Message
from utils import restful, zlcache
import string, random

bp = Blueprint("cms", __name__, url_prefix='/cms')

@bp.route('/')
#登陆装饰器具
@login_required
def index():
    return render_template('cms/cms_index.html')
#注销
@bp.route('/logout/')
@login_required
def logout():
    del session[config.CMS_USER_ID]
    return redirect(url_for('cms.login'))
#登录
class LoginView(views.MethodView):

    def get(self,message=None):
        return render_template('cms/cms_login.html', message=message)

    def post(self):
        form = LoginForm(request.form)
        if(form.validate()):
            email = form.email.data
            password = form.password.data
            remember = form.remember.data
            user = CMSUser.query.filter_by(email=email).first()
            if user and user.check_password(password):
                session[config.CMS_USER_ID]=user.id
                if remember:
                    """
                    设置为True ,那么session中的信息过期时间为31天
                    """
                    session.permanent=True
                return redirect(url_for('cms.index'))
            else:
                return self.get(message='邮箱或密码错误')
        else:
            message = form.get_error()
            return restful.params_error(message)

#个人中心
@bp.route('/profile/')
@login_required
def profile():
    return render_template('cms/cms_profile.html')


#修改密码
class ResetPwdView(views.MethodView):
    #登陆限制
    decorators = [login_required]
    def get(self):
        return render_template('cms/cms_resetpwd.html')

    def post(self):
        form = RestpwdForm(request.form)
        if form.validate():
            oldpwd = form.oldpwd.data
            newpwd = form.newpwd.data
            user = g.cms_user
            if user.check_password(oldpwd):
                user.password = newpwd
                db.session.commit()
                return restful.success()
            else:
                return restful.params_error('旧密码错误')

        else:
            message = form.get_error()
            return restful.params_error('message')

#发送邮件
@bp.route('/email_captcha/')
def email_captcha():
    #期望得到的url :/email_captcha/?email=xxxx@qq.com
    email = request.args.get('email')
    if not  email:
        return restful.params_error('请传递邮箱参数!')

    #给这个邮箱发送邮件
    #验证码
    source = list(string.ascii_letters)
    source .extend(map(lambda x:str(x),range(0, 10)))
    captcha ="".join(random.sample(source,6))

    #发送给用户
    message = Message('demoFootman论坛邮箱验证码', recipients=[email], body='您的邮箱验证码是 %s'%captcha)

    try:
        mail.send(message)
    except:
        #如果有问题，就报服务器内部错误
        return restful.server_error()
    #缓存数据
    zlcache.set(email, captcha)

    return restful.success()

#修改邮箱
class ResetEmailView(views.MethodView):
    decorators = [login_required]
    def get(self):
        return  render_template('cms/cms_resetemail.html')
    def post(self):
        form = ResetEmailForm(request.form)
        if form.validate():
            email = form.email.data
            g.cms_user_email = email
            db.session.commit()
            return restful.success()
        else:
            return restful.params_error(form.get_error())

#g 对象
@bp.before_request
def before_ruquest():
    if config.CMS_USER_ID in session:
        user_id = session.get(config.CMS_USER_ID)
        user = CMSUser.query.get(user_id)
        if user:
            g.cms_user = user


bp.add_url_rule('/login/',view_func=LoginView.as_view('login'))
bp.add_url_rule('/resetpwd/',view_func=ResetPwdView.as_view('resetpwd'))
bp.add_url_rule('/resetemail/',view_func=ResetEmailView.as_view('resetemail'))